<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-09-17 09:03:33
 * @LastEditors: LDY dong2406@126.com
 * @LastEditTime: 2022-09-20 09:56:10
 */

namespace Ldy\Traits\Form\Element;

use Closure;

trait Rows{

    protected $rows = [];

    protected $rowKey = -1;

    protected $colAttrs = [];
    /**
     * 行
     *"type": "el-row",
     *"props": {
     * "gutter": 10,
     * "type": "flex",
     * "justify": "start",
     * "align": "top"
     *},
     * @param array $attr 行属性
     * @return $this
     */
    public function rows(Array $props = [], Array $attr = []){
        $tmp = ['type'=>'el-row',"props"=>["gutter" => 10],'children'=>[]];
        $attr = $this->__merge($tmp, $attr);

        if(!empty($props)) $attr['props'] = $props;

        $this->rows[] = $attr;
        
        //行指针
        $this->rowKey++;

        //清空列属性
        $this->colAttrs = [];

        return $this;
    }

    /**
     * 列
     *
     * @param Closure $callback 闭包
     * @return $this
     */
    public function col(Closure $callback){

        $attr = ['type'=>'col', 'props'=>['span'=>12],"children"=>[]];

        //rule更改前
        $beforeRule = $this->form['rule'];

        call_user_func($callback, $this);

        $res = [];

        //执行闭包后
        if(count($beforeRule) == 0){
            //执行闭包之前没表单元素 之后直接取执行后的rule
            $res = $this->form['rule'];
        }else{
            //执行闭包之前有表单元素的情况下，通过差集获取属于列的表单元素
            $res = array_diff_key($this->form['rule'], $beforeRule);
        }

        $chidren = [];
        foreach($res as $v) $chidren[] = $v;
        $attr['children'] = $chidren;

        if(!empty($this->colAttrs)) $attr = $this->__merge($attr, $this->colAttrs);
        
        $this->rows[$this->rowKey]['children'][] = $attr;
        
        return $this;
    }

    /**
     * 设置属性
     *
     * @param array $props
     * "span": 12,
     * "offset": 0,
     * "push": 0,
     * "pull": 0
     * 
     * @param array $attr
     * @return void
     */
    public function setColAttr(Array $props = [], Array $attr = []){
        if(!empty($attr)) $this->colAttrs = $attr;
        if(!empty($props)) $this->colAttrs['props'] = $props;
        return $this;
    }
}